const app = getApp()
Page({
  data: {
    publishDisplay: 'block',
    getDisplay: 'none',
    onDisplay: 'none',
    myPublishedOrdersInfo: [],
    myGotOrdersInfo: [],
    hasOrders: false,
    permitCancel: false,
    publishClicked: 'publishClicked',
    getClicked: '',
    socketOpen: false
  },
  onLoad: function(options) {
    var that = this;
    if (app.globalData.phone == null) {
      var random = Math.floor(Math.random() * 100000);
      wx.connectSocket({
        url: 'ws://' + app.globalData.host + '/websocket/' + random
      })
    } else {
      wx.connectSocket({
        url: 'ws://' + app.globalData.host + '/websocket/' + app.globalData.phone
      })
    }
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开！')
      that.setData({
        socketOpen: true
      })
    })
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败，请检查！')
    })
    if (app.globalData.sessionId == null) {
      wx.showModal({
        title: '请先登录',
        content: '你尚未登录，请登录后再操作',
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.navigateTo({
              url: '/pages/user/login/login',
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    } else {
      // 在回调函数里面使用this要换成that
     wx.showLoading({
       title: '加载中',
       mask: true
     });
      
      wx.request({
        url: 'http://' + app.globalData.host + '/my/published/orders',
        header: {
          'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        method: 'GET',
        data: {
          sessionId: app.globalData.sessionId
        },
        success: function(res) {
          if (res.data.code == 1) {
            that.setData({
              myPublishedOrdersInfo: res.data.data
            });
          }
          wx.request({
            url: 'http://' + app.globalData.host + '/my/got/orders',
            header: {
              'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
            method: 'GET',
            data: {
              sessionId: app.globalData.sessionId
            },
            success: function (res) {
              if (res.data.code == 1) {
                that.setData({
                  myGotOrdersInfo: res.data.data
                });
              } else if (res.data.code == 2) {
                
              } else {

              }
            }
          });
          wx.hideLoading();
        }
      });
      
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
  },

  onShow: function() {
    if (app.globalData.sessionId == null) {
      wx.showModal({
        title: '请先登录',
        content: '你尚未登录，请登录后再操作',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.navigateTo({
              url: '/pages/user/login/login',
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    }
    // 下拉刷新数据不需要在这里写东西

    var that = this;
    wx.onSocketMessage(function (res) {
      console.log(res.data);
      that.setData({
        receivedMessage: res.data
      });
      if (res.data === '有新订单发布') {
        wx.showModal({
          title: '提示',
          content: '有新订单发布，要去看一下吗？',
          success: function (res) {
            if (res.confirm) {
              console.log('去看新订单');
              wx.navigateTo({
                url: '../getOrders/getOrders',
              })
            } else {
              console.log('不去看新订单');
            }
          }
        })
      } else if (res.data === '我的订单发生变更') {
        wx.showModal({
          title: '提示',
          content: '你的订单发生变更',
          success: function (res) {
            if (res.confirm) {
              console.log('刷新');
              that.reLoadMyOrders();
            } else {
              console.log('刷新');
              that.reLoadMyOrders();
            }
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '出错了！',
          success: function (res) {
            if (res.confirm) {

            } else {

            }
          }
        })
      }
      
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.closeSocket();

    wx.onSocketClose(function (res) {
      console.log('WebSocket 已关闭！')
    });

    wx.onSocketError(function (res) {
      console.log('WebSocket连接关闭失败，请检查！')
    });
  },

  reLoadMyOrders: function() {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    var that = this;
    wx.request({
      url: 'http://' + app.globalData.host + '/my/published/orders',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      method: 'GET',
      data: {
        sessionId: app.globalData.sessionId
      },
      success: function (res) {
        if (res.data.code == 1) {
          that.setData({
            myPublishedOrdersInfo: res.data.data
          });
        }
        wx.request({
          url: 'http://' + app.globalData.host + '/my/got/orders',
          header: {
            'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
          },
          method: 'GET',
          data: {
            sessionId: app.globalData.sessionId
          },
          success: function (res) {
            if (res.data.code == 1) {
              that.setData({
                myGotOrdersInfo: res.data.data
              });
            }
          }
        });
        // 停止下拉动作
        wx.stopPullDownRefresh();
        wx.hideLoading();
        wx.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1000
        });
      },
      fail: function () {
        // 隐藏导航栏加载框
        wx.hideNavigationBarLoading();
        // 停止下拉动作
        wx.stopPullDownRefresh();
      }
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.reLoadMyOrders();
  },
  comment: function(e) {
    var businessId = e.currentTarget.dataset.businessid;
    console.log("评论businessid：" + businessId);
    wx.navigateTo({
      url: '/comment/comment?businessId=' + businessId
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  callCustomer:function(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.customerphone
    });
  },
  callBusiness: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.businessphone
    });
  },
  publishButton: function() {  
    wx.showLoading({
      title: '加载中',
    });  
    this.setData({
      hasOrders: false,
      getDisplay: 'none',
      onDisplay: 'none',
      publishDisplay: 'block',
      publishClicked: 'publishClicked',
      getClicked: ''
    });
    wx.hideLoading();
  },
  getButton: function() {  
    wx.showLoading({      
      title: '加载中',
    });  
    this.setData({
      hasOrders: false,
      getDisplay: 'block',
      onDisplay: 'none',
      publishDisplay: 'none',
      publishClicked: '',
      getClicked: 'getClicked'
    });
    wx.hideLoading();
  },
  cancel: function (e) {
    var phone;
    var that = this;
    // 如果当前是顾客点击取消按钮需要联系抢单人
    if (e.currentTarget.dataset.customerphone == app.globalData.phone) {
      phone = e.currentTarget.dataset.businessphone; 
    } else {
      // 如果当前是抢单人点击取消按钮需要联系顾客
      phone = e.currentTarget.dataset.customerphone;
    }
    console.log('e.currentTarget.dataset.orderstatus: ' + e.currentTarget.dataset.orderstatus);
    console.log(phone);
    // 判断是否允许拨打电话弹出对话框
    if (e.currentTarget.dataset.orderstatus == 2) {
      // 允许弹出
      if (this.data.permitCancel == false) {
        wx.showModal({
          title: '提示',
          content: '请先联系对方再取消',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.makePhoneCall({
                phoneNumber: phone
              });
              that.setData({
                permitCancel: true
              });
            } else if (res.cancel) {
              console.log('用户点击取消，不取消')

            } else {

            }
          }
        });
      }
    } else {
        // 直接取消
        this.setData({
          permitCancel: true
        });
    }
    if (this.data.permitCancel == true) {
      wx.request({
        url: 'http://' + app.globalData.host + '/cancel/order',
        header: {
          'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        method: 'POST',
        data: {
          sessionId: app.globalData.sessionId,// 传入用户信息
          businessId: e.currentTarget.dataset.text// 传入订单信息
        },
        success: function (res) {
          if (res.data.code == 1) {
            wx.showToast({
              title: '取消成功',
              icon: 'success',
              duration: 2000
            });
            // 页面重定向，重新加载数据
            wx.redirectTo({
              url: '../myOrders/myOrders',
            });
          } else {
            wx.showToast({
              title: '取消出错',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: function () {
          wx.showToast({
            title: '取消失败',
            icon: 'none',
            duration: 2000
          });
        }
      }); 
    }
       
  },
  payOrder:function(e) {
    var businessId = e.currentTarget.dataset.businessid;
    var orderAmount = e.currentTarget.dataset.orderamount;
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    console.log("当前时间戳为：" + timestamp);

    // 发起支付
    // wx.requestPayment(
    //   {
    //     'timeStamp': timestamp,
    //     'nonceStr': 'abcd',
    //     'package': 'prepay_id=wx2017033010242291fcfe0db70013231072',
    //     'signType': 'MD5',
    //     'paySign': '',
    //     'success': function (res) { },
    //     'fail': function (res) { },
    //     'complete': function (res) { }
    //   })

    // 假设支付成功后模拟的操作
    wx.showModal({
      title: '确认支付？',
      content: '以下为模拟支付,你将支付' + orderAmount + '元',
      success: function(res) {
        if (res.confirm) {
          wx.request({
            url: 'http://' + app.globalData.host + '/pay',
            header: {
              'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
            method: 'POST',
            data: {
              payChannel: '微信支付',
              escrowTradeNo: '1000050301201807272320401628962',
              businessId: businessId// 传入订单信息
            },
            success: function (res) {
              if (res.data.code == 1) {
                wx.showToast({
                  title: '支付成功',
                  icon: 'success',
                  duration: 1500
                });
                wx.redirectTo({
                  url: './myOrders',
                });
              } else {
                wx.showModal({
                  title: '支付失败',
                  content: '发生未知错误，请稍后再试，或联系客服。',
                  success: function (res) {
                    if (res.confirm) {
                      wx.redirectTo({
                        url: './myOrders',
                      });
                    } else if (res.cancel) {
                      wx.redirectTo({
                        url: './myOrders',
                      });
                    }
                  }
                })
              }
            }
          })
        } else {
          console.log('取消支付');
          wx.showToast({
            title: '已取消支付',
            icon: 'none',
            duration: 800
          });
        }
      }
    });    
  }
})